package com.FrameWork.Common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.ShutterCallback;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.FrameWork.Utils.Utils;
import com.SFA.R;

public class CameraActivity extends AbstractBaseActivity implements
		SurfaceHolder.Callback {
	private final static String TAG = "CameraActivity";
	private ImageView surfaceView;
	private SurfaceHolder surfaceHolder;
	private Camera camera;
	private byte[] data;
	private Button btnSave;
	private ImageButton btnCapture;
	private String strPath;
	public static OnGetImageListener listener;
	private Bitmap bitmap;
	public static byte[] oldBitmap = null;
	private BitmapDrawable drawable;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

		WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.cameraactivity);
		surfaceView = (ImageView) findViewById(R.id.camera_preview); // Camera
		// interface
		// to
		// instantiate
		// components
		// surfaceHolder = surfaceView.getHolder(); // Camera interface to
		// instantiate components
		// surfaceHolder.addCallback(this); // Add a callback for the
		// SurfaceHolder
		// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		btnCapture = (ImageButton) findViewById(R.id.save_pic);
		btnCapture.setImageResource(android.R.drawable.ic_menu_camera);
		btnCapture.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Capture();
			}
		});
		btnSave = (Button) findViewById(R.id.btn_save);
		btnSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (data == null) {
					finish();
				} else {
					surfaceView.setImageBitmap(null);
					if (bitmap != null && !bitmap.isRecycled()) {
						bitmap.recycle();
						bitmap = null;
					}
					drawable = null;
					if (listener != null) {
						listener.onGetImage(data);
						listener = null;
					}
					finish();
				}
			}
		});
		if (oldBitmap != null) {
			//drawable = new BitmapDrawable(oldBitmap);
			surfaceView.setImageBitmap(BitmapFactory.decodeByteArray(oldBitmap, 0, oldBitmap.length, null));
			btnSave.setText("返回");
			btnSave.setEnabled(true);
		} else {
			btnSave.setEnabled(false);
			Capture();
		}
	}

	private void Capture() {
		// takePic();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		strPath = Environment.getExternalStorageDirectory() + File.separator;
		File path = new File(strPath);
		if (!path.exists())
			path.mkdirs();
		strPath = strPath + "photo.jpg";
		File file = new File(strPath);
		Uri uri = Uri.fromFile(file);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		startActivityForResult(intent, 1);
		overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			try {
				// 重新读入图片，注意这次要把options.inJustDecodeBounds设为false哦
				bitmap = Utils.getResizedImage(strPath, 500);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				File f = new File(strPath);
				f.delete();
				//drawable = new BitmapDrawable(bitmap);
				surfaceView.setImageBitmap(bitmap);
				this.data = baos.toByteArray();
				Log.w("SIZE", String.valueOf(this.data.length));
				baos.close();
				baos = null;
				btnSave.setEnabled(true);
				btnSave.setText("保存");
				System.gc();

			} catch (Exception err) {
				err.printStackTrace();
			}

		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_CAMERA
				|| keyCode == KeyEvent.KEYCODE_SEARCH) {
			takePic();
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			listener = null;
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			drawable = null;
			finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void takePic() {
		// camera.stopPreview();// stop the preview
		camera.takePicture(null, null, pictureCallback); // picture
	}

	// Photo call back
	Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
		// @Override
		public void onPictureTaken(byte[] data, Camera camera) {
			if (listener != null) {
				listener.onGetImage(data);
				listener = null;
			}
			finish();
		}
	};

	private ToneGenerator tone;

	// 快门按下的时候onShutter()被回调
	private ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {
			if (tone == null)
				// 发出提示用户的声音
				tone = new ToneGenerator(AudioManager.STREAM_MUSIC,
						ToneGenerator.MAX_VOLUME);
			tone.startTone(ToneGenerator.TONE_PROP_BEEP2);
		}
	};

	public void surfaceCreated(SurfaceHolder holder) {
		Log.i(TAG, "surfaceCallback====");
		camera = Camera.open(); // Turn on the camera
		try {
			camera.setPreviewDisplay(holder); // Set Preview
		} catch (IOException e) {
			camera.release();// release camera
			camera = null;
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.i(TAG, "====surfaceChanged");
		Camera.Parameters parameters = camera.getParameters(); // Camera
		// parameters to
		// obtain
		parameters.setPictureFormat(PixelFormat.JPEG);// Setting Picture Format
		
		parameters.set("rotation", 90);
		parameters.setFocusMode("auto");
		camera.setParameters(parameters); // Setting camera parameters
		camera.startPreview(); // Start Preview
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.i(TAG, "====surfaceDestroyed");
		camera.stopPreview();// stop preview
		camera.release(); // Release camera resources
		camera = null;
	}

}
